<?php

class SiteController extends Controller {

    public $layout = 'column1';

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        if (!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
            throw new CHttpException(500, "This application requires that PHP was compiled with Blowfish support for crypt().");

        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionIndex() {

        //$this->redirect(Yii::app()->homeUrl);
        $this->actionNew();
    }
	
	
    public function genPassword() {

        return rand(1000, 1000000);
    }

    public function actionNew() {		
		$order = new Order;
		//$order->newOrder();
		//$order->beforeCreate();
		
		$registr = new RegistrationForm;
		$profile = new Profile;
		
		
		//нужна проверка того, что поль-ль авторизован, что поль-ль уже существует
		//ссылка на личный кабинет в письмо
		if(isset($_POST['Order']))
		{
			//$registr->username = $_POST['Order']['phone'];
                        $registr->username = 'wezze'.$this->genPassword();
			$registr->email=$_POST['Order']['email'];
			$profile->firstname=($_POST['Order']['fio']);

			$password = $this->genPassword();
			$registr->password = $password;
			$registr->verifyPassword = $registr->password;

			$profile->phone = $_POST['Order']['phone'];
			//$soucePassword = $registr->password;
			$registr->activkey=UserModule::encrypting(microtime().$registr->password);
			$registr->password=UserModule::encrypting($registr->password);
			$registr->verifyPassword=UserModule::encrypting($registr->verifyPassword);
			$registr->superuser=0;
			$registr->status=1;
						
			if ($registr->save()) {
                                $registr->username = 'wezze'.$registr->id;
                                $registr->save();
				$profile->user_id=$registr->id;
				$profile->save();
				UserModule::sendMail($registr->email,UserModule::t("You registered from {site_name}",array('{site_name}'=>Yii::app()->name)),UserModule::t("Ваш логин: ".$registr->username.'. Ваш пароль: '.$password,array('{activation_url}'=>$activation_url)));
							
				$order->user_id = $registr->id;
			}
			else
			{
				//var_dump($registr->errors);
				throw new CHttpException(400,'Не зарегистрировался');
			}
			
			//$order->user_id = 1;
			
			//var_dump($order->user_id);
			$order->articul = $_POST['Order']['articul'];
			$order->is_adaptate = $_POST['Order']['is_adaptate'];
			/*var_dump($order->save());
			var_dump($order->errors);*/
			if ($order->save())
			{
				$order->newOrder();
				$order->managerSee();
				$order->save();
				$this->redirect('/order/site/created');
			}
			else
			{
				var_dump($order->errors);
				throw new CHttpException(400,'Заказ не создан');
			}
		}
		else
		{
			$this->render('new');
		}
    }
	
	public function actionCreated() {

        $this->render('created', array());
    }

    public function actionList() {
        $orders = Order::model()->findAll();

        $this->render('list', array('orders' => $orders));
    }

    public function actionNewOrder($id) {
        $order = Order::model()->findByPk($id);
        $order->newOrder();
		
		$order->managerSee();
		$order->save();
    }

    public function actionApprove($id) {
        $order = Order::model()->findByPk($id);
        $order->approve();
        $order->save();
    }

    public function actionDecline($id) {
        $order = Order::model()->findByPk($id);
        $order->decline('Фоток мало');
        $order->save();
    }

    public function actionPay($id) {
        $order = Order::model()->findByPk($id);
        $order->pay();
        $order->save();
    }

    public function actionMake($id) {
        $order = Order::model()->findByPk($id);
        $order->make('http://vimeo.com/123123');
        $order->save();
    }

    public function actionClose($id) {
        $order = Order::model()->findByPk($id);
        $order->close();
        $order->save();
    }
	
	public function actionManagerSee($id) {
        $order = Order::model()->findByPk($id);
        $order->managerSee();
        $order->save();
    }

    /*

      newOrder approve decline pay make close
     */
}
